package com.example.controller;

import com.example.config.MyService;
import com.example.dto.SentenceGrade;
import com.example.dto.SignRecordResult;
import com.example.mp3ToWav.Mp3ToWav;
import com.example.service.SignRecordService;
import com.example.voiceEvaluation.VoiceEvaluation;
import com.example.dto.Result;
import com.example.entity.Sentence;
import com.example.dto.SentenceResult;
import com.example.entity.User;
import com.example.service.RecordService;
import com.example.service.SentenceService;
import com.example.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
@Api("用户相关操作")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SentenceService sentenceService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private MyService myService;
    @Autowired
    private SignRecordService signRecordService;

    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
    @ApiOperation(value = "获取用户信息", notes = "返回结果(is_signIn)说明：true表示当天已经签到，false表示还没有签到")
    @ResponseBody
    public Result<User> getUser(@RequestParam("userId") String userId){
        Result<User> result = new Result<>();
        User user = userService.getUser(userId);
        return result.ok("用户数据", user);
    }

    @ResponseBody
    @ApiOperation(value = "签到调用api", notes = "传递参数：用户id（userId）")
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public void signIn(@RequestParam("userId") String userId){
        userService.signIn(userId);
        signRecordService.signIn(userId);
    }

    @ResponseBody
    @ApiOperation(value = "获取历史签到记录", notes = "传递参数：用户id（userId）")
    @RequestMapping(value = "/getSignDays", method = RequestMethod.POST)
    public Result<SignRecordResult> getSignDays(@RequestParam("userId") String userId){
        Result<SignRecordResult> result = new Result<>();
        SignRecordResult list = signRecordService.getSignRecordByUserId(userId);
        return result.ok("用户历史签到记录", list);
    }

    @RequestMapping(value = "/sendToUser", method = RequestMethod.POST)
    @ApiOperation(value = "发送录音文件给服务端", notes = "文件标识：file，句子Id：sentenceId")
    @ResponseBody
    public Result<SentenceGrade> fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("sentenceId") String sentenceId,
                                            @RequestParam("userId") String userId) throws IOException {
        Result<SentenceGrade> result = new Result<>();
        SentenceGrade sentenceGrade = new SentenceGrade();
        if(file.isEmpty()){
            return null;
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = simpleDateFormat.format(new Date());
        String path = myService.getPersonalAudioPath() + today ;
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        Sentence sentence = sentenceService.getSentenceById(sentenceId);
        String text=sentence.getContent();
        String path2=myService.getPersonalAudioPath() + today + "/" +fileName;
        String path3= Mp3ToWav.mp3ToWav(path2);
        List<SentenceResult> res = VoiceEvaluation.voiceEvaluation(text,path3);
        double highScore = recordService.saveRecord(res, userId, sentenceId);
        sentenceGrade.setSentence(res.get(0));
        sentenceGrade.getSentence().setHighScore(highScore);
        res.remove(0);
        sentenceGrade.setWords(res);
        return result.ok("录音测评结果", sentenceGrade);
    }

    @ResponseBody
    @ApiOperation(value = "登陆时发送用户Id给服务器", notes = "发送的用户ID标识为：code")
    @RequestMapping(value = "/sendUserId", method = RequestMethod.POST)
     public Result<String> getUserId(@RequestParam("code") String code){
        Result<String> result = new Result<>();
        String userId = userService.getUserId(code);
        return result.ok("返回用户Id", userId);
    }
}
